use std::error::Error;
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use serde::{Deserialize, Serialize};
use crate::types::Object;
use crate::types::response::UnixResponse;

#[derive(Debug)]
pub struct Client {
    stream:TcpStream,
}

impl Default for Client {
    fn default() -> Self {
        let addr = "127.0.0.1:25500";
        let l = TcpStream::connect(addr).unwrap();

        Client{ stream:l }
    }
}

impl Client {
    pub fn new(addr:&str) -> Self {
        let l = TcpStream::connect(addr).unwrap();

        Client{ stream:l }
    }

    pub fn do_request(&mut self,data:Vec<u8>) -> Result<UnixResponse,Box<dyn Error>> {
        self.stream.write(data.as_slice())?;
        let mut buf = [0;1024*30];

        let len = self.stream.read(&mut buf)?;
        let v = buf[..len].to_vec();
        let str = String::from_utf8(v)?;
        let data = serde_json::from_str(str.as_str())?;

        Ok(data)
    }
}

#[cfg(test)]
mod test {
    use crate::client::tcp::Client;
    use crate::types::pod::Pod;
    use crate::types::request::UnixRequest;

    #[test]
    fn test() {
       let mut c =  Client::new("192.168.189.136:25500");
       let req = UnixRequest{
           name: "busybox-78644c6f64-4b24k".to_string(),
           namespace: "default".to_string(),
           typ: "pod".to_string()
       };
       let data = c.do_request(req.to_vec()).unwrap();
       let v=  serde_json::to_value(data).unwrap();
       println!("{}",serde_json::to_string(&v).unwrap());
    }
}